#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 23:56:57 2013

@author: nicola
"""

import os

from collections import Sequence

from kelindo.core.folder import Folder
from kelindo.core.folder import FolderError
from kelindo.core.classifier import MBClassifier
from kelindo.core.finalizer import Finalizer

class Collection(Sequence):
    """ This class manages a collection of folders """
    
    def __init__(self):
        self.folders = []
        return

    def __getitem__(self, index):
        return self.folders[index]

    def __len__(self):
        return len(self.folders)

    def __repr__(self):      
        out = []
        for f in self.folders:
            out.append(f.__repr__())
        return '\n'.join(out)  

    def add(self, dir_list):
        """ Adds folders to the collection """
        for d in dir_list:
            for root, dirs, files in os.walk(d):
                self.folders.append(Folder.folder_factory(root))

    def classify(self):
        """ Classifies folders of the collection """
        mbc = MBClassifier()
        for folder in self:
            try:
                mbc.classify(folder)
            except FolderError:
                pass
        return
        
    def finalize(self):
        """ Finalizes folders of the collection """
        fnl = Finalizer()
        for folder in self:
            try:
                fnl.finalize(folder)
            except FolderError:
                pass
        return   

    def remove(self, path):
        """ Removes a specific folder, given its path """
        for index in range(len(self)):
            if path == self[index].path:
                self.folders.pop(index)
        return

    def update(self, path):
        """ Updates a specific folder, given its path """
        f = Folder.folder_factory(path)
        mbc = MBClassifier()
        try:
            mbc.classify_folder(f)
            for index in range(len(self)):
                if path == self[index].path:
                    self[index] = f
        except FolderError:
            pass
        return

    def check_conflicts(self):
        """ Checks for conflicts (duplicate folders) """
        return
        
        
    
    